<template>
  <div>

    <!-- 按钮操作 -->
    <el-row :gutter="24">
      <el-col :span="24">
        <el-card shadow="always" style="text-align: left">
          <el-button type="primary" size="small" @click="addOrUpdate('')">新增角色</el-button>
          <el-button type="danger" size="small" @click="batchDel">批量删除</el-button>
        </el-card>
      </el-col>
    </el-row>

    <br>

    <!-- 数据列表 -->
    <el-row :gutter="24">
      <el-col :span="24">
        <el-card shadow="always">
          <el-table :data="tableData" border style="width: 100%" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="50"></el-table-column>
            <el-table-column prop="roleName" label="角色"></el-table-column>
            <el-table-column prop="remarks" label="备注"></el-table-column>
            <el-table-column label="操作" width="130">
              <template slot-scope="scope">
                <el-button type="text" size="small" @click="addOrUpdate(scope.row.id)">编辑</el-button>
                <el-button type="text" size="small" @click="addRole(scope.row.id)">赋予权限</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>

    <!-- 添加或修改 -->
    <el-dialog :title="title" :visible.sync="dialogFormVisible" style="text-align: left;">
      <el-form :model="addForm" :rules="rules" ref="addForm">
        <el-form-item label="角色名" prop="roleName" :label-width="formLabelWidth">
          <el-input v-model="addForm.roleName" autocomplete="off" style="width: 220px;"></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remarks" :label-width="formLabelWidth">
          <el-input v-model="addForm.remarks" autocomplete="off" style="width: 220px;"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="resetForm('addForm')">取 消</el-button>
        <el-button type="primary" @click="submitForm('addForm')">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 赋予角色 -->
    <el-dialog title="赋予权限" :visible.sync="addMenuShow" style="text-align: left" :before-close="closeAddMenu">
      <el-tree
        :data="menuData"
        show-checkbox
        default-expand-all
        node-key="id"
        ref="tree"
        highlight-current
        :default-checked-keys="treeEcho"
        :props="defaultProps">
      </el-tree>
      <div slot="footer" class="dialog-footer">
        <el-button @click="resetChecked">清空</el-button>
        <el-button type="primary" @click="submitAddMenu()">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
  import {get, post} from '@/api/http.js'

  export default {
    name: "role",

    // 页面加载就执行
    mounted: function () {
      this.getListData();
    },

    // 双向数据绑定
    data() {
      return {
        // 表格数据
        tableData: [],

        // 列表多选数据ID集合
        selectIds: [],

        // 添加或修改弹出框
        title: '添加角色',
        bizId: '',
        dialogFormVisible: false,
        formLabelWidth: '120px',
        addForm: {
          roleName: '',
          remarks: ''
        },
        // 表单校验
        rules: {
          roleName: [
            {required: true, message: '请输入角色', trigger: 'blur'},
          ]
        },

        // 树形菜单数据
        menuData: [],
        // 自定义字段值
        defaultProps: {
          children: 'children',
          label: 'label'
        },

        // 赋予权限
        addMenuShow: false,

        // 赋予权限时的回显
        treeEcho: []

      }
    },

    // 方法区
    methods: {
      // 关闭添加角色回调
      closeAddMenu(done) {
        this.bizId = '';
        this.$refs.tree.setCheckedKeys([]);
        done()
      },

      // 执行赋予权限
      submitAddMenu() {
        let menuIds = this.$refs.tree.getCheckedKeys();
        if (menuIds.length === 0) {
          this.$message({
            message: '请至少选中一个权限',
            type: 'warning'
          });
          return;
        }
        let param = {id: this.bizId, menus: menuIds.toString()};
        get("/admin/role/addMenu", param)
          .then(res => {
            this.$message({
              message: '权限赋予成功',
              type: 'success'
            });
            this.addMenuShow = false;
            this.bizId = '';
            this.$refs.tree.setCheckedKeys([]);
          })
          .catch(err => {
            this.$message({
              message: '权限赋予失败',
              type: 'error'
            });
          })
      },

      // 清空选中的权限
      resetChecked() {
        this.$refs.tree.setCheckedKeys([]);
      },

      // 赋予权限
      addRole(id) {
        this.bizId = id;
        this.addMenuShow = true;

        // 获取树形结构权限列表
        get('/admin/menu/tree', '')
          .then(res => {
            this.menuData = res.data;
          })
          .finally(() => {
            // 回显数据
            get('/admin/role/getRoleMenu/' + id, '')
              .then(res1 => {
                this.treeEcho = res1.data;
              })
          })
      },

      // 提交添加表单
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          // 表单验证是否通过
          if (valid) {
            let uri = "";
            let msg = "";
            if (this.bizId === '') {
              uri = "/admin/role/add";
              msg = "恭喜你，角色添加";
            } else {
              uri = "/admin/role/update";
              msg = "恭喜你，角色修改";
            }
            // 发起请求
            post(uri, this.addForm)
              .then(res => {
                this.$message({
                  message: msg + '成功',
                  type: 'success'
                });
              })
              .catch(err => {
                this.$message({
                  message: msg + '失败',
                  type: 'error'
                });
              })
              .finally(() => {  // 请求响应之后在执行
                // 关闭添加或修改弹出出框
                this.dialogFormVisible = false;
                this.bizId = '';
                this.resetForm('addForm');
                this.getListData();
              })
          } else {
            return false;
          }
        });
      },

      // 重置表单
      resetForm(formName) {
        this.dialogFormVisible = false;
        this.bizId = '';
        this.$refs[formName].resetFields();
      },

      // 添加或修改弹出对话框
      addOrUpdate(id) {
        this.bizId = id;
        this.dialogFormVisible = true;
        if (id !== '') {
          get("/admin/role/get/" + id, '')
            .then(res => {
              this.addForm = res.data;
            })
            .catch(err => {

            })
            .finally(() => {

            })
        }
      },

      // 表格数据多选,获取ID
      handleSelectionChange(val) {
        // val 传给的是数组，里面放的是选中当前行的所有数据
        // console.info(val);
        // 声明一个空数组，将val遍历获取每一行数据的ID，放入集合
        let idsArr = new Array();
        val.forEach(row => {
          idsArr.push(row.id)
        });
        // 赋值给全局变量
        this.selectIds = idsArr;
      },

      // 批量删除
      batchDel() {
        if (this.selectIds.length === 0) {
          this.$message({
            type: 'warning',
            message: '请至少选择一条数据'
          });
          return;
        }
        // 调用删除方法
        this.delData(this.selectIds.toString());
      },

      // 删除数据
      delData(id) {
        this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let param = {ids: id};
          get('/admin/role/del', param)
            .then(res => {
              this.$message({
                type: 'success',
                message: '删除成功'
              });
            })
            .catch(err => {
              this.$message({
                type: 'error',
                message: '删除失败'
              });
            }).finally(() => {
            this.getListData();
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },

      // 获取列表数据
      getListData() {
        post("/admin/role/list", '')
          .then(res => {
            this.tableData = res.data;
          })
          .catch(err => {

          })
          .finally(() => {

          })
      }
    }
  }
</script>

<style scoped>

</style>
